import { defineStore } from 'pinia'
import { fetchLogin, fetchUserInfo, fetchLevelList } from '@/service/user'
import { LoginParams, UserInfo } from '@/service/user/type'
import { fetchSystemConfig } from '@/service/index'
const initState = { nickname: '', avatar: '' }

interface UserState {
  userInfo: UserInfo
  token: string
  viewDuration: {
    time?: string
    duration: number
  }
  shareCode: string
  welcomeConfig: {
    content?: string
    title?: string
    showDialog?: number
  }
  systemConfig: Record<string, any>
}

export default defineStore('user', {
  state: (): UserState => ({
    userInfo: { ...initState },
    token: '',
    viewDuration: {
      time: '',
      duration: 0,
    },
    shareCode: '',
    welcomeConfig: {},
    systemConfig: {},
  }),
  getters: {
    isLogin(state) {
      return !!state.token
    },
  },
  actions: {
    getSystemConfig() {
      fetchSystemConfig().then((res) => {
        this.systemConfig = res.data
        console.log(this.systemConfig, '系统细致')
      })
    },
    setShareCode(code) {
      this.shareCode = code
    },
    setViewDuration(payload: UserState['viewDuration']) {
      this.viewDuration = {
        ...this.viewDuration,
        ...payload,
      }
    },
    clearInfo() {
      this.userInfo = null
      this.token = ''
    },
    updateWelcomeConfig(v: UserState['welcomeConfig']) {
      this.welcomeConfig = v
    },
    // 更新打卡状态
    updateClockStatus(status: number | boolean) {
      this.userInfo.clock_status = status
    },
    updateUserInfo(info: UserInfo) {
      this.userInfo = info
    },
    updateToken(token: string) {
      this.token = token
    },
    login(params: LoginParams) {
      fetchLogin(params).then((res) => {
        this.userInfo = res.data
        this.token = res.data.token
      })
    },
    async getUserInfo() {
      const res = await fetchUserInfo()
      const levelRes = await fetchLevelList()
      const { distributionLevel } = res.data
      const { lists } = levelRes.data as any
      if (lists && Array.isArray(lists)) {
        const lv = lists.findIndex((item) => item.id == distributionLevel.id)
        res.data.level = lv + 1
      }
      this.userInfo = res.data
    },
  },
  persist: true,
})
